package datalookin.fragment;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import datalookin.activity.MainWaterActivity;
import datalookin.activity.MainWaterActivity2;
import datalookin.adapter2.HistoryStationAdapter;
import datalookin.adapter2.RealStationAdapter;
import datalookin.dto2.StationAllDataDto;
import datalookin.dto2.StationDataDto;
import datalookin.network2.GetHistoryDataByIdType;
import datalookin.network2.GetRealStationDataAction;
import datalookin.network2.GetWaterPlantData;
import inter.Delegate;
import main.dto.Commontype;
import main.dto.Stationnumposition;
import utils.TimeUtil;

/**
 * Created by Administrator on 2016/6/5.
 */
public class HistoryStationFragment extends Fragment {

    ListView lv_history;
    Spinner spinner_type;

    String selectedType;

    TextView tv_date;

    TextView tv_date2;

    TextView tv_emptyView;

    List<StationDataDto> stationDataDtos = new ArrayList<StationDataDto>();
    HistoryStationAdapter historyStationAdapter = new HistoryStationAdapter();
    {
        historyStationAdapter.setStationDataDtos(stationDataDtos);
    }

    String str_date = TimeUtil.currentDate();
    String str_date2 = TimeUtil.currentDate();
    private View btn_search;

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == tv_date)
            {
                pickDate();
            }

            else if (v == tv_date2)
            {
                pickDate2();
            }

            else if (v == btn_search)
            {
                search();
            }
        }
    };

    private void search() {
        stationDataDtos.clear();
        // 若不是胡家畈水厂则返回
        MainWaterActivity2 mainWaterActivity = (MainWaterActivity2) getActivity();
        if (!mainWaterActivity.getWaterPlantName().contains("胡家畈"))
        {
            Toast.makeText(MyApplication.share(),"暂无数据",Toast.LENGTH_SHORT).show();
            return;
        }


        for(final Stationnumposition stationnumposition:MyApplication.mobileUserDto.getStationnumpositions())
        {
            if(stationnumposition.getStationnum().endsWith("00"))continue;
            GetHistoryDataByIdType getWaterPlantData = new GetHistoryDataByIdType();
            getWaterPlantData.setDelegate(new Delegate() {
                @Override
                public void onResponse(String response) {
                    if (!response.startsWith("[")){
                        finishIt();
                        return;
                    }
                    List<StationDataDto> tmp = JSON.parseArray(response,StationDataDto.class);
                    stationDataDtos.addAll(tmp);
                    historyStationAdapter.notifyDataSetChanged();

                    finishIt();

                }

                private void finishIt() {
                    ((UIHandler.BaseActivity) getActivity()).closeDialog();
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                    finishIt();
                }
            });

            getWaterPlantData.setId(stationnumposition.getStationnum());
            getWaterPlantData.setType(selectedType.split("\\(")[0]);
            getWaterPlantData.setBeginTime(str_date.replace("-","/"));
            getWaterPlantData.setEndTime(str_date2.replace("-","/"));
            getWaterPlantData.get();


            ((UIHandler.BaseActivity) getActivity()).showDialog();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_historystation,null);
        initview(view);
        return view;
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyApplication.share(), R.layout.simple_spinner_item);
    {
        for(Commontype commontype: MyApplication.mobileUserDto.getCommontypes())
        {
            if (commontype.getId() != null)
                adapter.add(commontype.getId().getType());
        }
    }

    private void initview(View view) {
        lv_history = (ListView) view.findViewById(R.id.id_lv_historyplant);
        lv_history.setAdapter(historyStationAdapter);

        spinner_type = (Spinner) view.findViewById(R.id.id_spinner_type);
        spinner_type.setAdapter(adapter);
        spinner_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                selectedType = adapter.getItem(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        tv_date = (TextView) view.findViewById(R.id.id_tv_date);

//        SpannableString msp = new SpannableString(str_date);
//        msp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bluelight)), 0, str_date.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
//        msp.setSpan(new UnderlineSpan(), 0, str_date.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_date.setText(str_date);
        tv_date.setOnClickListener(onClickListener);

        tv_date2 = (TextView) view.findViewById(R.id.id_tv_date2);
//        tv_date2.setText(TimeUtil.currentDate());
//        SpannableString msp2 = new SpannableString(str_date2);
//        msp2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bluelight)), 0, str_date2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
//        msp2.setSpan(new UnderlineSpan(), 0, str_date2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_date2.setText(str_date2);
        tv_date2.setOnClickListener(onClickListener);

        btn_search = view.findViewById(R.id.id_btn_search);
        btn_search.setOnClickListener(onClickListener);

        tv_emptyView = (TextView) view.findViewById(R.id.id_tv_empty);
        lv_history.setEmptyView(tv_emptyView);
    }



    private void pickDate() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 指定一个日期
        Date date = null;
        try {
            date = dateFormat.parse(str_date + " "+ "00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 对 calendar 设置为 date 所定的日期
        c.setTime(date);
        Dialog dialog = new DatePickerDialog(
                getActivity(),
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                        setDate(year, month, dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
        );
        dialog.show();
    }

    private void setDate(int year, int month, int dayOfMonth) {
        String str = "";
        int i = month + 1;
        if (i >=0 && i <=9)
        {
            str = "0"+i;
        }
        else
        {
            str = i+"";
        }

        String dayofmonth_0 = "";
        if (dayOfMonth < 10)
            dayofmonth_0 = "0";

        str_date = year+"-"+str+"-"+ dayofmonth_0 + dayOfMonth;
        tv_date.setText(str_date);
//        TextUtil.setLinkLike(tv_date, str_date);

    }



    private void pickDate2() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 指定一个日期
        Date date = null;
        try {
            date = dateFormat.parse(str_date2 +" " + "00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 对 calendar 设置为 date 所定的日期
        c.setTime(date);
        Dialog dialog = new DatePickerDialog(
                getActivity(),
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                        setDate2(year,month,dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
        );
        dialog.show();
    }

    private void setDate2(int year, int month, int dayOfMonth) {
        String str = "";
        int i = month + 1;
        if (i >=0 && i <=9)
        {
            str = "0"+i;
        }
        else
        {
            str = i+"";
        }

        String dayofmonth_0 = "";
        if (dayOfMonth < 10)
            dayofmonth_0 = "0";
        str_date2 = year+"-"+str+"-"+dayofmonth_0+dayOfMonth;
        tv_date2.setText(str_date2);
//        TextUtil.setLinkLike(tv_date2, str_date2);
    }






    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

   
}
